from apps.common.base.views import *
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao

class J99APIViewSet(BaseViewSet):

    apikey = 'F679CBFA7B41C45DA106C02DF5783847'
    @action(methods=['post'], detail=False, authentication_classes=[],permission_classes=[])
    def getItemDetail(self, request):
        params = getRequestParams(request)
        scene = params.get('scene')
        if not scene:
            return Response(response_message('scene不能为空'))
        itemValue = params.get('itemValue')
        if not itemValue:
            return Response(response_message('itemValue不能为空'))
        itemid = ''
        itemData = {}
        skuList = []
        if scene == 'jd':
            arr = itemValue.split('/')
            if len(arr) == 1:
                itemid = arr[0]
            else:
                itemid = arr[len(arr)-1].split('.')[0]
            url = 'https://api09.99api.com/jd/detail'
            query = {'apikey': self.apikey, 'itemid': itemid}
            res = requests.get(url, params=query)
            resDict = json.loads(res.content)
            item = {}
            if resDict.get('retcode') and resDict.get('retcode') == '0000':
                item = resDict.get('data').get('item')
                itemData = {
                    'name': item.get('name'),
                    'coverPhotos': json.dumps(item.get('images')),
                    'detailPhotosRichText': item.get('desc'),
                    'status': 0
                }
                skuList = item.get('sku')
            else:
                return Response(response_message(resDict.get('data')))
        elif scene == 'taobao':
            arr = itemValue.split('?')
            if len(arr) == 1:
                itemid = arr[0]
            else:
                for a in arr[1].split('&'):
                    if 'id=' in a:
                        itemid = a.split('=')[1]
            url = 'https://api09.99api.com/jd/detail'
            query = {'apikey': self.apikey, 'itemid': itemid}
            res = requests.get(url, params=query)
            resDict = json.loads(res.content)
            print('resDict', resDict)
            return Response(response_success('操作成功'))
        elif scene == 'tiammao':
            url = 'https://api09.99api.com/jd/detail'
            query = {'apikey': self.apikey, 'itemid': params.get('itemid')}
            res = requests.get(url, params=query)
            resDict = json.loads(res.content)
            return Response(response_success('操作成功'))
        # 创建商品和对应的sku
        if not itemData.get('name'):
            return Response(response_message('商品采集失败'))
        item_obj = ItemDao().create(itemData)
        if len(skuList) > 0:
            for sku in skuList:
                sku['item'] = item_obj.id
                if sku.get('skuNum'):
                    sku['skuNum'] = sku.get('skuNum')
                else:
                    sku['skuNum'] = str(random_num(4)) + '-' + str(item_obj.id)
                if sku.get('imagePath'):
                    sku['coverUrl'] = sku.get('imagePath')
                else:
                    sku['coverUrl'] = json.loads(item_obj.coverPhotos)[0] if item_obj.coverPhotos else ''

                specValues = []
                for key in item.get('saleProp'):
                    specValue = {}
                    specValue['specName'] = item.get('saleProp').get(str(key))
                    specValue['name'] = sku.get(str(key))
                    specValues.append(specValue)
                sku['specValues'] = json.dumps(specValues, ensure_ascii=False).replace(' ','')
                SkuDao().create(sku)
        if item_obj:
            return Response(response_action(10001, item_obj.id))
        else:
            return Response(response_message('商品创失败'))
        